// 拖拽排序功能
function initDragAndDrop() {
    const container = document.getElementById('laborProcessContainer');
    let draggedElement = null;
    let placeholder = null;

    // 为每个可拖拽的卡片添加事件监听器
    container.addEventListener('dragstart', function(e) {
        // 只允许从card-header或drag-handle开始拖拽
        const isFromHeader = e.target.classList.contains('card-header') || 
                           e.target.classList.contains('drag-handle') ||
                           e.target.closest('.card-header');
        
        if (isFromHeader && e.target.closest('.draggable-card')) {
            draggedElement = e.target.closest('.draggable-card');
            draggedElement.classList.add('dragging');
            
            // 创建占位符
            placeholder = document.createElement('div');
            placeholder.className = 'drop-zone';
            placeholder.innerHTML = '<p style="text-align: center; margin: 40px 0; color: #999;">拖拽到此处</p>';
            
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/html', draggedElement.outerHTML);
        } else {
            // 阻止其他区域的拖拽
            e.preventDefault();
        }
    });

    container.addEventListener('dragend', function(e) {
        // 清理所有可能的拖拽状态，确保万无一失
        console.log('Dragend triggered');
        
        // 方法1：通过全局变量清理
        if (draggedElement) {
            console.log('Cleaning via draggedElement:', draggedElement);
            draggedElement.classList.remove('dragging');
            draggedElement = null;
        }
        
        // 方法2：查找并清理所有可能的dragging元素
        const draggingElements = container.querySelectorAll('.dragging');
        draggingElements.forEach(element => {
            console.log('Force cleaning dragging element:', element);
            element.classList.remove('dragging');
        });
        
        // 清理占位符和插入指示器
        if (placeholder && placeholder.parentNode) {
            placeholder.parentNode.removeChild(placeholder);
        }
        placeholder = null;
        
        // 清理所有插入指示器
        clearInsertIndicators();
    });

    container.addEventListener('dragover', function(e) {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';

        // 清除所有现有的插入指示器
        clearInsertIndicators();

        const afterElement = getDragAfterElement(container, e.clientX, e.clientY);
        
        // 创建细线插入指示器
        const insertIndicator = createInsertIndicator();
        
        if (afterElement == null) {
            // 插入到最后
            container.appendChild(insertIndicator);
        } else {
            // 插入到指定元素前
            container.insertBefore(insertIndicator, afterElement);
        }
    });

    container.addEventListener('drop', function(e) {
        e.preventDefault();
        
        // 找到插入指示器的位置
        const insertIndicator = container.querySelector('.insert-indicator');
        
        if (draggedElement && insertIndicator) {
            // 在指示器位置插入拖拽的元素
            insertIndicator.parentNode.insertBefore(draggedElement, insertIndicator);
            
            // 立即清理dragging状态，确保视觉正常
            draggedElement.classList.remove('dragging');
            
            // 添加成功动画效果
            const elementToAnimate = draggedElement;
            elementToAnimate.style.transform = 'scale(1.05)';
            setTimeout(() => {
                if (elementToAnimate) {
                    elementToAnimate.style.transform = '';
                }
            }, 200);
        }
        
        // 清理所有插入指示器
        clearInsertIndicators();
    });
}

// 获取拖拽后应该插入的位置（支持行列布局）
function getDragAfterElement(container, x, y) {
    const draggableElements = [...container.querySelectorAll('.draggable-card:not(.dragging)')];
    
    if (draggableElements.length === 0) {
        return null;
    }
    
    // 按DOM顺序排序所有元素（这样能保持正确的逻辑顺序）
    draggableElements.sort((a, b) => {
        const rectA = a.getBoundingClientRect();
        const rectB = b.getBoundingClientRect();
        
        // 先按行排序（top位置），再按列排序（left位置）
        const rowDiff = rectA.top - rectB.top;
        if (Math.abs(rowDiff) < 20) { // 同一行（考虑小的偏差）
            return rectA.left - rectB.left;
        }
        return rowDiff;
    });
    
    // 计算最佳插入位置
    let bestElement = null;
    let bestDistance = Infinity;
    
    for (let i = 0; i < draggableElements.length; i++) {
        const element = draggableElements[i];
        const rect = element.getBoundingClientRect();
        
        // 计算鼠标到元素中心的距离
        const elementCenterX = rect.left + rect.width / 2;
        const elementCenterY = rect.top + rect.height / 2;
        const distance = Math.sqrt(Math.pow(x - elementCenterX, 2) + Math.pow(y - elementCenterY, 2));
        
        // 如果鼠标在元素左半部分，考虑插入到此元素前面
        if (x < elementCenterX && distance < bestDistance) {
            bestElement = element;
            bestDistance = distance;
        }
        // 如果鼠标在元素右半部分，考虑插入到下一个元素前面（即当前元素后面）
        else if (x >= elementCenterX) {
            // 找到下一个元素作为插入点
            if (i + 1 < draggableElements.length) {
                const nextElement = draggableElements[i + 1];
                const nextRect = nextElement.getBoundingClientRect();
                const nextDistance = Math.sqrt(Math.pow(x - (nextRect.left + nextRect.width / 2), 2) + Math.pow(y - (nextRect.top + nextRect.height / 2), 2));
                
                if (nextDistance < bestDistance) {
                    bestElement = nextElement;
                    bestDistance = nextDistance;
                }
            } else {
                // 如果是最后一个元素，插入到最后
                bestElement = null;
                break;
            }
        }
    }
    
    return bestElement;
}

// 创建插入指示器
function createInsertIndicator() {
    const indicator = document.createElement('div');
    indicator.className = 'insert-indicator';
    indicator.innerHTML = '<p style="text-align: center; margin: 15px 0; color: #007bff; font-weight: bold;">⬇ 拖拽到此处 ⬇</p>';
    return indicator;
}

// 清除所有插入指示器
function clearInsertIndicators() {
    const indicators = document.querySelectorAll('.insert-indicator');
    indicators.forEach(indicator => indicator.remove());
}

// 在DOM加载完成后初始化拖拽功能
document.addEventListener('DOMContentLoaded', function() {
    initDragAndDrop();
    
    // 添加拖拽相关的CSS样式
    const style = document.createElement('style');
    style.textContent = `
        .draggable-card {
            transition: all 0.3s ease;
            position: relative;
        }

        .draggable-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .draggable-card.dragging {
            opacity: 0.5;
            transform: rotate(5deg);
        }

        .card-header[draggable="true"] {
            cursor: move;
        }

        .card-header[draggable="true"]:hover {
            background-color: rgba(0,123,255,0.05);
        }

        .drag-handle {
            color: #999;
            font-size: 12px;
            margin-right: 8px;
            cursor: grab;
            user-select: none;
        }

        .drag-handle:hover {
            color: #007bff;
        }

        .drag-handle:active {
            cursor: grabbing;
        }

        .insert-indicator {
            border: 2px dashed #007bff;
            background-color: rgba(0,123,255,0.1);
            border-radius: 8px;
            min-height: 60px;
            margin: 8px;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            pointer-events: none;
            animation: insertPulse 1.5s infinite alternate;
            position: relative;
            width: calc(33.33% - 16px); /* 匹配卡片宽度 */
            box-sizing: border-box;
        }
        
        @keyframes insertPulse {
            from { 
                background-color: rgba(0,123,255,0.1);
                border-color: #007bff;
            }
            to { 
                background-color: rgba(0,123,255,0.2);
                border-color: #0056b3;
            }
        }
    `;
    document.head.appendChild(style);
});
